package com.zjpg.forum.controller;

import com.zjpg.forum.common.AppResult;
import com.zjpg.forum.common.ResultCode;
import com.zjpg.forum.config.AppConfig;
import com.zjpg.forum.model.*;
import com.zjpg.forum.services.IArticleReplyService;
import com.zjpg.forum.services.IArticleService;
import com.zjpg.forum.services.IBoardService;
import com.zjpg.forum.services.IThumbListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ArticleController
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/8/13 23:40
 */
@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleReplyService articleReplyService;

    @Resource
    private IThumbListService thumbListService;

    /**
     * 发布新帖子
     *
     * @param boardId 板块Id
     * @param title   文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户是否被禁言
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 板块的校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        // 分装文章对象
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        articleService.create(article);
        return AppResult.success();
    }

    /**
     * 获取各个板块文章信息
     *
     * @param boardId
     * @return
     */
    @GetMapping("/getAllByBoardId")
    @ApiOperation("查询各板块帖子列表")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块ID") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles;
        if (boardId == null) {
            articles = articleService.selectAll(null);
        } else {
            articles = articleService.selectAll(boardId);
        }
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    /**
     * 查询帖子详情信息
     *
     * @return
     */
    @GetMapping("/details")
    @ApiOperation("查询帖子详情信息")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        // 获取session信息
        HttpSession session = request.getSession(false);
        // 获取用户信息
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 调用service，获取帖子详情
        Article article = articleService.getDetailById(id);
        // 判断帖子是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (user.getId() == article.getUserId()) {
            article.setAuthor(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @PostMapping("/modify")
    @ApiOperation("编辑修改帖子")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        log.info(user.toString());
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.getById(id);
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.modify(id, title, content);
        log.warn("帖子更新成功，Article id = " + id + ", userId = " + user.getId() + ".");
        return AppResult.success();
    }

    /*@ApiOperation("帖子点赞")
    @PostMapping("/thumbsup")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }*/
    @ApiOperation("帖子点赞")
    @PostMapping("/thumbsup")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        ThumbList thumbList =  thumbListService.selectByPrimaryKey(id,
                user.getId());
        //System.out.println(thumbList);
        if (thumbList == null) {
            ThumbList newThumbList = new ThumbList();
            newThumbList.setArticleId(id);
            newThumbList.setThumbUserId(user.getId());
            newThumbList.setState(1L);
            articleService.thumbsUpById(id);
            thumbListService.insertSelective(newThumbList);
            return AppResult.success();
        }
        if (thumbList.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_FULL_LIKECOUNT);
        }
        articleService.thumbsUpById(id);
        thumbListService.updateByPrimaryKeySelective(thumbList);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.getById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户ID") @RequestParam(value = "userId",required = false) Long userId) {
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
